<template>
    <el-drawer title="我是标题" :visible.sync="dialogVisible" :with-header="false" size='720px' class="demand_box" @close="resetForm('addMtVedioForm')">
        <AddMtInfo />
        <AddMtInfoBulk />
        <div class="flexbox flexcolumn height_100">
            <div class="demand_head flexbox flexcenter flexbetween">
                <span class="demand_title">上传素材</span>
                <span class="icon_btn icon_btn_32"><img src="@/assets/img/close_check.svg" alt="" @click="resetForm('addMtVedioForm')"></span>
            </div>
            <div class="demand_center flex">
                <!-- <el-upload
                    drag
                    action="a"
                    :on-change="ReadFileMD5"
                    :http-request="UploadSceneModel"
                    :auto-upload="false"
                    multiple
                >
                <i class="el-icon-upload" />
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload> -->
                <el-form label-position="top" style="margin-top:-10px" :model="addMtVedioForm" size="medium" :hide-required-asterisk='true' ref="addMtVedioForm" :rules="addMtVedioRules" class="dialog_form">
                    <el-form-item label="" prop="">
                        <el-upload class="video_loader" ref="upload" drag :show-file-list="false" accept=".mp4,.MP4" :http-request="videoUploadRequest" multiple :limit="99" :on-change="handleChange" :before-upload="beforeVideoUpload" :disabled="tableData.length>=99">
                            <div class="pot_content flexbox flexcenter">
                                <img src="@/assets/img/pot_video.svg" alt="">
                                <span class="pot_text">点击上传 或直接将视频文件拖入此区域</span>
                                <span class="pot_tips">视频大小不超过 100MB，视频格式为 MP4</span>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div class="has_load_title flexbox flexcenter flexbetween">
                    <span class="font_16 color_01">上传列表</span>
                    <el-button class="plain_blue" icon="el-icon-circle-plus-outline" size="small" :disabled="move_loading" @click="addMtInfoBulk">批量设置名称</el-button>
                </div>
                <el-table :data="tableData" class="com_table" style="margin-top:20px">
                    <div slot="empty" class="flexbox flexcenter flexcolumn flexjust" style="height:300px">
                        <img src="@/assets/img/null_icon.svg" alt="">
                        <div class="font_13 color_03">暂无数据</div>
                    </div>
                    <el-table-column prop="full_name" label="素材">
                        <template slot-scope="scope">
                            <div class="flexbox flexcenter">
                                <div class="vd_left">
                                    <!-- <video :src="scope.row.material" class="vd_poster" v-if="scope.row.material"></video>
                                    <img src="@/assets/img/no_img.png" alt="" class="vd_poster" v-else> -->
                                    <img :src="scope.row.material+'&x-oss-process=video/snapshot,t_0,f_jpg'" alt="" class="vd_poster" v-if="scope.row.material">
                                    <img src="@/assets/img/no_img.png" alt="" class="vd_poster" v-else>
                                </div>

                                <div class="vd_center flex">
                                    <template v-if="scope.row.material==''">
                                        <el-link :underline="false" type="danger">原文件名:</el-link>{{scope.row.material_name}}
                                    </template>
                                    <template v-else>
                                        <el-link :underline="false" type="primary">新素材名:</el-link>{{scope.row.material_name}}
                                    </template>
                                    <!-- <div class="no_name flexbox flexcenter" @click="addMtInfo(scope.row,scope.$index)" v-else>
                                        生成名称
                                        <img src="@/assets/img/no_name.png" style="margin-left:2px;margin-top:-1px" alt="">
                                    </div> -->
                                </div>
                                <div class="vd_right">
                                    <el-link type="primary" :disabled="move_loading" :underline="false" @click="addMtInfo(scope.row,scope.$index)"><i class="el-icon-edit" style="font-size:18px"></i></el-link>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="product_num" label="进度" width="230">
                        <template slot-scope="scope">
                            <span class="font_14 color_02" v-if="scope.row.process==0">等待上传,请先设置名称</span>
                            <div v-else>
                                <el-progress :percentage="scope.row.process" :stroke-width="10"></el-progress>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="product_num" label="操作" width="92">
                        <template slot-scope="scope">
                            <el-link type="primary" :underline="false" :disabled="move_loading" @click="deletTable(scope.$index)">移除</el-link>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="demand_footer flexbox flexcenter">
                <el-button plain size="small" class="el-button-width" @click="resetForm()">取 消</el-button>
                <el-button type="primary" size="small" class="el-button-width" @click="submitForm()" :loading="loading" :disabled='loading'>完成创建</el-button>
            </div>
        </div>
    </el-drawer>
</template>

<script>
import AddMtInfo from "./AddMtInfo";
import AddMtInfoBulk from "./AddMtInfoBulk";
import { clientInfo,clientTos,tosLink } from "@/assets/js/oss";
import SparkMD5 from "spark-md5";
export default {
    name: "",
    data() {
        return {
            loading: false,
            dialogVisible: false,
            move_loading: false,
            tableData: [],
            addMtVedioRules: {},
        };
    },
    created() {
        this.$bus.on("addMtVedio", (value) => {
            this.dialogVisible = value.dialogVsb;
        });
    },
    beforeDestroy() {
        this.$bus.off("addMtVedio");
    },
    methods: {

        // 提交
        async submitForm() {
            if (this.tableData.length == 0) {
                this.$message.error("请先选择视频");
                return;
            }
            for (let i in this.tableData) {
                if (!this.tableData[i].material) {
                    this.$message.error("请完善视频信息");
                    return;
                }
            }
            this.loading = true;
            let list = [];
            for (let i in this.tableData) {
                list.push({
                    material_md5: this.tableData[i].material_md5,
                    material_name: this.tableData[i].material_name,
                    description: this.tableData[i].description,
                    photographer_uid: this.tableData[i].photographer_uid,
                    director_uid: this.tableData[i].director_uid,
                    editor_uid: this.tableData[i].editor_uid,
                    centre_uid: this.tableData[i].centre_uid,
                    material: this.tableData[i].material,
                    product_name: this.tableData[i].product_name,
                    product_id: this.tableData[i].product_id,
                    brand_name: this.tableData[i].brand_name,
                    brand_id: this.tableData[i].brand_id,
                    business_scene: this.tableData[i].business_scene,
                    channel: this.tableData[i].channel,
                    area: this.tableData[i].area,
                    material_type: this.tableData[i].material_type,
                    duration: this.tableData[i].duration,
                    width: this.tableData[i].width,
                    height: this.tableData[i].height,
                    primary_name:this.tableData[i].primary_name
                });
            }
            // console.log(list);
            // return;
            const { data: res } = await this.$http.post(
                "adminapi/Materialv2/materialUpload",
                {
                    list: list,
                }
            );
            if (res.code !== 200) {
                this.$message.error(res.msg);
                this.loading = false;
                return;
            } else {
                this.$message({
                    message: "创建成功",
                    type: "success",
                });
                this.loading = false;
                this.$parent.getDataList(1);
                this.resetForm();
            }
        },

        beforeVideoUpload(file) {
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "MP4" || testmsg === "mp4";
            const isLt2M = file.size / 1024 / 1024 < 100;
            if (!extension) {
                this.$message({
                    message: "上传视频只能是mp4 / MP4格式!",
                    type: "error",
                });
                return false;
            }
            if (!isLt2M) {
                this.$message({
                    message: "上传文件大小不能超过 100MB!",
                    type: "error",
                });
                return false;
            }

            return extension || isLt2M;
        },

        videoUploadRequest(file) {
            console.log(file);
            let that = this;
            let videoSrc = URL.createObjectURL(file.file);
            let videoElement = document.createElement("video");
            videoElement.src = videoSrc;
            videoElement.addEventListener("loadedmetadata", function (v) {
                URL.revokeObjectURL(videoSrc);
                let sizeVal =
                    videoElement.videoWidth / videoElement.videoHeight ==
                        16 / 9 ||
                    videoElement.videoWidth / videoElement.videoHeight ==
                        9 / 16;
                if (Math.round(videoElement.duration) <= 4) {
                    that.$message.error("视频时长不能少于4s");
                    return;
                }
                if (!sizeVal) {
                    that.$message.error("视频尺寸比例不正确");
                    return;
                }
                if (that.tableData.length >= 99) {
                    return;
                }

                //md5方法2
                var fileReader = new FileReader();
                var dataFile = file.file;
                var spark = new SparkMD5();
                fileReader.readAsBinaryString(dataFile);
                fileReader.onload = function (e) {
                    spark.appendBinary(e.target.result);
                    var md5 = spark.end();
                    let is_repeat = that.tableData.some((item) => {
                        if (item.material_md5 == md5) {
                            return true;
                        }
                    });
                    if (is_repeat) {
                        that.$message.error("视频已选择，请勿重复上传");
                        return;
                    } else {
                        that.tableData.push({
                            material_md5: md5,
                            file: file.file,
                            brandSelect: {},
                            description:"",
                            productSelect: {},
                            width: videoElement.videoWidth,
                            height: videoElement.videoHeight,
                            duration: Math.round(videoElement.duration),
                            area: 1,
                            material_type:2,
                            channel: "",
                            business_scene: "",
                            brand_id: "",
                            brand_name: "",
                            product_id: "",
                            product_name: "",
                            material: "",
                            centre_uid: "",
                            editor_uid: "",
                            director_uid: "",
                            photographer_uid: "",
                            material_name: file.file.name,
                            material: "",
                            process: 0,
                            primary_name:file.file.name.slice(0,-4)
                        });
                    }

                    that.$refs.upload.clearFiles();
                };
            });
        },

        //移除列表
        deletTable(index) {
            this.tableData.splice(index, 1);
        },

        async uploadSingle(option, name, index) {
            const that = this;
            this.move_loading = true;
            this.loading = true;
            try {
                const client = clientInfo;
                const clienttos = clientTos
                let file = option;
                let nowData = new Date();
                let year = nowData.getFullYear();
                let month =
                    nowData.getMonth() + 1 < 10
                        ? "0" + (nowData.getMonth() + 1)
                        : nowData.getMonth() + 1;
                let date =
                    nowData.getDate() < 10
                        ? "0" + nowData.getDate()
                        : nowData.getDate();
                let getData = year + "-" + month + "-" + date;
                let relativePath = "source4.0/" + getData + "/";
                let fileName = name + ".mp4";
                const ret = await clienttos.putObject({
                    key: relativePath + fileName,
                    body: file,
                    progress: (p, cpt) => {
                        that.tableData[index].process = Math.floor(p * 100);
                    },
                });
                if (ret.statusCode === 200) {
                    let url = tosLink+relativePath + encodeURIComponent(fileName)
                    var timestamp = new Date().getTime();
                    let vdUrl = url + "?v=" + timestamp;
                    this.tableData[index].material = vdUrl;
                    this.move_loading = false;
                    this.loading = false;
                } else {
                    this.loading = false;
                    this.move_loading = false;
                    this.$message.error("上传失败！");
                }
                // let ret = await client.multipartUpload(
                //     relativePath + fileName,
                //     file,
                //     {
                //         progress: function (p) {
                //             that.tableData[index].process = Math.floor(p * 100);
                //         },
                //     }
                // );
                // if (ret.res.statusCode === 200) {
                //     let url = ret.res.requestUrls[0];
                //     let urlstr = url.substring(0, url.lastIndexOf("?"));
                //     var timestamp = new Date().getTime();
                //     let vdUrl = urlstr + "?v=" + timestamp;
                //     this.tableData[index].material = vdUrl;
                //     this.move_loading = false;
                //     this.loading = false;
                // } else {
                //     this.loading = false;
                //     this.move_loading = false;
                //     this.$message.error("上传失败！");
                // }
            } catch (error) {
                this.loading = false;
                this.move_loading = false;
                this.$message.error("上传失败！");
            }
            this.move_loading = false;
            this.loading = false;
        },

        // 批量上传
        async uploadMulti(name, info) {
            console.log(info)
            for (let i in this.tableData) {
                this.move_loading = true;
                this.loading = true;
                this.tableData[i].material_name = name[i];
                this.tableData[i].brandSelect = info.brandSelect;
                this.tableData[i].description = info.description;
                this.tableData[i].productSelect = info.productSelect;
                this.tableData[i].area = info.area;
                this.tableData[i].material_type = info.material_type;
                this.tableData[i].channel = info.channel;
                this.tableData[i].business_scene = info.business_scene;
                this.tableData[i].brand_id = info.brand_id;
                this.tableData[i].brand_name = info.brand_name;
                this.tableData[i].product_id = info.product_id;
                this.tableData[i].product_name = info.product_name;
                this.tableData[i].material = info.material;
                this.tableData[i].centre_uid = info.centre_uid;
                this.tableData[i].editor_uid = info.editor_uid;
                this.tableData[i].director_uid = info.director_uid;
                this.tableData[i].photographer_uid = info.photographer_uid;
                const that = this;
                try {
                    const client = clientInfo;
                    const clienttos = clientTos
                    let file = this.tableData[i].file;
                    let nowData = new Date();
                    let year = nowData.getFullYear();
                    let month =
                        nowData.getMonth() + 1 < 10
                            ? "0" + (nowData.getMonth() + 1)
                            : nowData.getMonth() + 1;
                    let date =
                        nowData.getDate() < 10
                            ? "0" + nowData.getDate()
                            : nowData.getDate();
                    let getData = year + "-" + month + "-" + date;
                    let relativePath = "source4.0/" + getData + "/";
                    let fileName = name[i] + ".mp4";
                    const ret = await clienttos.putObject({
                        key: relativePath + fileName,
                        body: file,
                        progress: (p, cpt) => {
                            that.tableData[i].process = Math.floor(p * 100);
                        },
                    });
                    if (ret.statusCode === 200) {
                        let url = tosLink+relativePath + encodeURIComponent(fileName)
                        let urlstr = url.substring(0, url.lastIndexOf("?"));
                        var timestamp = new Date().getTime();
                        let vdUrl = url + "?v=" + timestamp;
                        this.tableData[i].material = vdUrl;
                        this.loading = false;
                        this.move_loading = false;
                    } else {
                        this.loading = false;
                        this.move_loading = false;
                        this.$message.error("上传失败！");
                    }
                    // let ret = await client.multipartUpload(
                    //     relativePath + fileName,
                    //     file,
                    //     {
                    //         progress: function (p) {
                    //             that.tableData[i].process = Math.floor(p * 100);
                    //         },
                    //     }
                    // );
                    // if (ret.res.statusCode === 200) {
                    //     let url = ret.res.requestUrls[0];
                    //     let urlstr = url.substring(0, url.lastIndexOf("?"));
                    //     var timestamp = new Date().getTime();
                    //     let vdUrl = urlstr + "?v=" + timestamp;
                    //     this.tableData[i].material = vdUrl;
                    //     this.loading = false;
                    //     this.move_loading = false;
                    // } else {
                    //     this.loading = false;
                    //     this.move_loading = false;
                    //     this.$message.error("上传失败！");
                    // }
                } catch (error) {
                    this.loading = false;
                    this.move_loading = false;
                    this.$message.error("上传失败！");
                }
            }
            this.loading = false;
            this.move_loading = false;
        },

        // 设置名称
        addMtInfo(row, index) {
            const attr = {
                dialogVsb: true,
                index: index,
                info: row,
            };
            this.$bus.emit("addMtInfo", attr);
        },

        // 批量设置名称
        addMtInfoBulk() {
            if (this.tableData.length <= 0) {
                this.$message.error("请先选择视频");
                return;
            } else {
                const attr = {
                    dialogVsb: true,
                    quantity: this.tableData.length,
                };
                this.$bus.emit("addMtInfoBulk", attr);
            }
        },

        // 关闭重置表单
        resetForm() {
            this.tableData = [];
            this.$refs.upload.clearFiles();
            this.dialogVisible = false;
        },
    },
    components: {
        AddMtInfo,
        AddMtInfoBulk,
    },
};
</script>

<style scoped>
.pot_content {
    width: 100%;
    height: 181px;
    background-color: rgba(165, 177, 209, 0.08);
    border-radius: 12px;
    flex-direction: column;
    justify-content: center;
}
.pot_text {
    font-size: 13px;
    color: #25282c;
    line-height: 18px;
    margin-top: 12px;
}
.pot_tips {
    font-size: 13px;
    color: #828b99;
    margin-top: 4px;
    line-height: 18px;
}
.vd_poster {
    width: 42px;
    height: 60px;
    display: block;
    border-radius: 4px;
}
.vd_center {
    margin: 0 16px;
}
.no_name {
    width: 88px;
    height: 24px;
    border: 1px solid #fe6262;
    border-radius: 2px;
    justify-content: center;
    font-size: 13px;
    color: #fe6262;
    cursor: pointer;
}
</style>
<style>
.video_loader .el-upload {
    display: block;
}
.video_loader .el-upload-dragger {
    width: 100%;
    border: 0;
}
</style>


